package com.appisode.HAFSmenu;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;


public class HAFSmenuFetch extends Service {

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public HAFSmenuFetch() {
	      super();
	}
	private final String PATH="/data/data/com.HAFSmenu/";// put download file here
	
	public void DownloadFromURL(String dbURL, String fileName){ //this is downloader method
		try{
			URL url = new URL("http://hafsnewspaper.hosting.paran.com/xe/?module=file&act=procFileDownload&file_srl=91&sid=8f9d87f38198eaeac44a775b27854b1d");//target link
			File file = new File(PATH + fileName);
			long startTime = System.currentTimeMillis();
			Log.d("DB downloader", "download beginning");
			Log.d("DB downloader", "download url:"+url);
			Log.d("DB downloader", "downloaded file name:fileName");
			URLConnection ucon = url.openConnection();
			InputStream is = ucon.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			ByteArrayBuffer baf = new ByteArrayBuffer(50);
			int current = 0;
			while ((current=bis.read())!= -1){
				baf.append((byte) current);
			}
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(baf.toByteArray());
			fos.close();
			Log.d("DB downloader", "download ready in"+((System.currentTimeMillis()-startTime)/10000)+" sec");
			
		}
		catch (IOException e){
			Log.d("ImageManager","Error:"+e);
		}
		stopSelf();
	}
	protected void onHandleIntent(Intent intent) {
	      // Normally we would do some work here, like download a file.
	      // For our sample, we just sleep for 5 seconds.
	  }
	  public int onStartCommand(Intent intent, int flags, int startId) {
	      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

	      // For each start request, send a message to start a job and deliver the
	      // start ID so we know which request we're stopping when we finish the job

	      // If we get killed, after returning from here, restart
	      return START_STICKY;
	      
	  }
}